class MusicPlugin {
  constructor(options = {}) {
    // 默认参数
    const defaults = {
      showLyricOnInit: false,
      songs: [],
      autoCollapseTime: 5000,
      autoplay: false
    };
    this.options = Object.assign({}, defaults, options);
    this.songs = this.options.songs;
    this.current = 0;
    this.expanded = false;
    this.hideTimer = null;
    this.lyricData = [];
    this.lyricTimer = null;
    this.activeLyricIndex = -1;
    this.lyricList = null;
    this.init();
  }

  injectStyle() {
    if (document.getElementById('music-plugin-style')) return;
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'music-plugin.css';
    link.id = 'music-plugin-style';
    document.head.appendChild(link);
  }

  get icons() {
    return {
      play: `<svg width="28" height="28" viewBox="0 0 28 28"><polygon points="8,6 24,14 8,22" fill="#fff"/></svg>`,
      pause: `<svg width="28" height="28" viewBox="0 0 28 28"><rect x="7" y="6" width="5" height="16" fill="#fff"/><rect x="16" y="6" width="5" height="16" fill="#fff"/></svg>`,
      prev: `<svg width="22" height="22" viewBox="0 0 22 22"><polygon points="15,5 7,11 15,17" fill="#fff"/><rect x="5" y="5" width="2" height="12" fill="#fff"/></svg>`,
      next: `<svg width="22" height="22" viewBox="0 0 22 22"><polygon points="7,5 15,11 7,17" fill="#fff"/><rect x="15" y="5" width="2" height="12" fill="#fff"/></svg>`,
      lyric: `<svg width="22" height="22" viewBox="0 0 22 22"><rect x="4" y="6" width="14" height="2" fill="#fff"/><rect x="4" y="10" width="10" height="2" fill="#fff"/><rect x="4" y="14" width="8" height="2" fill="#fff"/></svg>`,
      hide: `<svg width="18" height="18" viewBox="0 0 18 18"><line x1="4" y1="4" x2="14" y2="14" stroke="#aaa" stroke-width="2"/><line x1="14" y1="4" x2="4" y2="14" stroke="#aaa" stroke-width="2"/></svg>`
    };
  }

  createLyricContainer() {
    const lyricContainer = document.createElement('div');
    lyricContainer.className = 'music-plugin-lyric-container';
    lyricContainer.innerHTML = `
      <div class="music-plugin-lyric-wrapper">
        <div class="music-plugin-lyric-list"></div>
      </div>
    `;
    document.body.appendChild(lyricContainer);
    return lyricContainer;
  }

  parseLyrics(lrcText) {
    const lyrics = [];
    const lines = lrcText.split('\n');
    const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;
    lines.forEach(line => {
      const match = line.match(timeRegex);
      if (match) {
        const minute = parseInt(match[1]);
        const second = parseInt(match[2]);
        const millisecond = parseInt(match[3]);
        const time = minute * 60 * 1000 + second * 1000 + millisecond;
        const text = line.replace(timeRegex, '').trim();
        if (text) {
          lyrics.push({ time, text });
        }
      }
    });
    lyrics.sort((a, b) => a.time - b.time);
    return lyrics;
  }

  createHTML() {
    const song = this.songs[0] || {};
    const container = document.createElement('div');
    container.className = 'music-plugin-container';
    container.innerHTML = `
      <div class="music-plugin-disc">
        <img src="${song.cover || ''}" alt="cover">
        <div class="music-plugin-play-btn">${this.icons.play}</div>
      </div>
      <div class="music-plugin-controls">
        <button class="music-plugin-hide-btn" title="收起">${this.icons.hide}</button>
        <div class="music-plugin-title">${song.title || ''}  ${song.artist || ''}</div>
        <div class="music-plugin-btns">
          <button class="music-plugin-prev-btn" title="上一首">${this.icons.prev}</button>
          <button class="music-plugin-toggle-btn" title="播放/暂停">${this.icons.play}</button>
          <button class="music-plugin-next-btn" title="下一首">${this.icons.next}</button>
          <button class="music-plugin-lyric-btn" title="歌词">${this.icons.lyric}</button>
        </div>
      </div>
      <audio class="music-plugin-audio" src="${song.src || ''}"></audio>
      <div class="music-plugin-progress-bar-outer">
        <div class="music-plugin-progress-bg">
          <div class="music-plugin-progress-glow"></div>
          <div class="music-plugin-progress"></div>
          <div class="music-plugin-progress-thumb"></div>
        </div>
      </div>
    `;
    // 图片加载处理
    const img = container.querySelector('img');
    img.addEventListener('error', function() { this.classList.add('error'); });
    img.addEventListener('load', function() { this.classList.remove('error'); });
    document.body.appendChild(container);
    return container;
  }

  formatTime(sec) {
    sec = Math.floor(sec);
    const m = Math.floor(sec / 60);
    const s = sec % 60;
    return `${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}`;
  }

  updateProgressBar() {
    const duration = this.audio.duration || 0;
    const current = this.audio.currentTime || 0;
    const percent = duration ? (current / duration) * 100 : 0;
    this.progress.style.width = percent + '%';
    this.progressThumb.style.left = percent + '%';
  }

  seek(e) {
    const rect = this.progressBg.getBoundingClientRect();
    let x = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left;
    x = Math.max(0, Math.min(x, rect.width));
    const percent = x / rect.width;
    const duration = this.audio.duration || 0;
    this.audio.currentTime = percent * duration;
    this.updateProgressBar();
  }

  updateDiscRotate() {
    const img = this.disc.querySelector('img');
    if (!this.audio.paused) {
      img.classList.add('rotating');
      img.classList.remove('paused');
      this.toggleBtn.innerHTML = this.icons.pause;
      this.playBtn.innerHTML = this.icons.pause;
    } else {
      img.classList.add('paused');
      this.toggleBtn.innerHTML = this.icons.play;
      this.playBtn.innerHTML = this.icons.play;
    }
  }

  loadLyrics(lyricPath) {
    if (this.lyricTimer) clearInterval(this.lyricTimer);
    this.lyricWrapper.classList.remove('show');
    if (!lyricPath) {
      this.lyricData = [];
      return;
    }
    fetch(lyricPath)
      .then(response => response.text())
      .then(lrcText => {
        this.lyricData = this.parseLyrics(lrcText);
        if (this.lyricData.length > 0) this.startLyricDisplay();
      })
      .catch(() => { this.lyricData = []; });
  }

  startLyricDisplay() {
    //this.lyricWrapper.classList.add('show');
    if (this.lyricTimer) clearInterval(this.lyricTimer);
    this.activeLyricIndex = -1;
    this.lyricList = this.lyricContainer.querySelector('.music-plugin-lyric-list');
    this.lyricList.innerHTML = '';
    this.lyricData.forEach((lyric) => {
      const lyricItem = document.createElement('div');
      lyricItem.className = 'music-plugin-lyric-item';
      lyricItem.textContent = lyric.text;
      lyricItem.dataset.time = lyric.time;
      this.lyricList.appendChild(lyricItem);
    });
    this.lyricTimer = setInterval(() => this.updateLyricDisplay(), 100);
  }

  updateLyricDisplay() {
    const currentTime = this.audio.currentTime * 1000;
    let newActiveIndex = -1;
    for (let i = 0; i < this.lyricData.length; i++) {
      if (currentTime >= this.lyricData[i].time) newActiveIndex = i;
      else break;
    }
    if (newActiveIndex !== this.activeLyricIndex) {
      if (this.activeLyricIndex >= 0) {
        const prevActiveItem = this.lyricList.children[this.activeLyricIndex];
        if (prevActiveItem) prevActiveItem.classList.remove('active');
      }
      this.activeLyricIndex = newActiveIndex;
      if (this.activeLyricIndex >= 0 && this.activeLyricIndex < this.lyricData.length) {
        const activeItem = this.lyricList.children[this.activeLyricIndex];
        if (activeItem) {
          activeItem.classList.add('active');
          const itemHeight = activeItem.offsetHeight;
          const scrollTop = this.activeLyricIndex * itemHeight + 5;
          this.lyricList.style.transform = `translateY(${-scrollTop}px)`;
        }
      }
    }
  }

  switchSong(idx) {
    this.current = (idx + this.songs.length) % this.songs.length;
    const song = this.songs[this.current];
    this.audio.src = song.src;
    this.disc.querySelector('img').src = song.cover;
    this.title.textContent = `${song.title}  ${song.artist}`;
    setTimeout(() => this.updateProgressBar(), 200);
    if (this.lyricData.length > 0) this.startLyricDisplay();
    else this.lyricList.innerHTML = '';
    this.loadLyrics(song.lyrics);
    this.audio.play();
    this.updateDiscRotate();
  }

  expand() {
    if (this.expanded) return;
    this.expanded = true;
    this.container.classList.add('expanded');
    clearTimeout(this.hideTimer);
  }

  collapse() {
    if (!this.expanded) return;
    this.expanded = false;
    this.container.classList.remove('expanded');
  }

  startHideTimer() {
    if (this.options.autoCollapseTime <= 0) return;
    clearTimeout(this.hideTimer);
    
    this.hideTimer = setTimeout(() => {
      this.collapse();
    }, this.options.autoCollapseTime);
  }

  init() {
    this.injectStyle();
    this.container = this.createHTML();
    this.lyricContainer = this.createLyricContainer();
    this.disc = this.container.querySelector('.music-plugin-disc');
    this.playBtn = this.container.querySelector('.music-plugin-play-btn');
    this.controls = this.container.querySelector('.music-plugin-controls');
    this.audio = this.container.querySelector('.music-plugin-audio');
    this.toggleBtn = this.container.querySelector('.music-plugin-toggle-btn');
    this.prevBtn = this.container.querySelector('.music-plugin-prev-btn');
    this.nextBtn = this.container.querySelector('.music-plugin-next-btn');
    this.lyricBtn = this.container.querySelector('.music-plugin-lyric-btn');
    this.title = this.container.querySelector('.music-plugin-title');
    this.hideBtn = this.container.querySelector('.music-plugin-hide-btn');
    this.progressBar = this.container.querySelector('.music-plugin-progress-bar-outer');
    this.progressBg = this.container.querySelector('.music-plugin-progress-bg');
    this.progress = this.container.querySelector('.music-plugin-progress');
    this.progressThumb = this.container.querySelector('.music-plugin-progress-thumb');
    this.progressGlow = this.container.querySelector('.music-plugin-progress-glow');
    this.lyricWrapper = this.lyricContainer.querySelector('.music-plugin-lyric-wrapper');

    // 进度条
    this.audio.addEventListener('timeupdate', () => this.updateProgressBar());
    this.audio.addEventListener('loadedmetadata', () => this.updateProgressBar());
    this.audio.addEventListener('durationchange', () => this.updateProgressBar());
    let dragging = false;
    const seek = (e) => this.seek(e);
    this.progressBg.addEventListener('mousedown', e => {
      dragging = true;
      seek(e);
      document.addEventListener('mousemove', seek);
      document.addEventListener('mouseup', () => {
        dragging = false;
        document.removeEventListener('mousemove', seek);
      }, { once: true });
    });
    this.progressBg.addEventListener('touchstart', e => {
      dragging = true;
      seek(e);
      document.addEventListener('touchmove', seek);
      document.addEventListener('touchend', () => {
        dragging = false;
        document.removeEventListener('touchmove', seek);
      }, { once: true });
    });
    this.progressThumb.addEventListener('mousedown', e => {
      e.stopPropagation();
      dragging = true;
      document.addEventListener('mousemove', seek);
      document.addEventListener('mouseup', () => {
        dragging = false;
        document.removeEventListener('mousemove', seek);
      }, { once: true });
    });
    this.progressThumb.addEventListener('touchstart', e => {
      e.stopPropagation();
      dragging = true;
      document.addEventListener('touchmove', seek);
      document.addEventListener('touchend', () => {
        dragging = false;
        document.removeEventListener('touchmove', seek);
      }, { once: true });
    });

    // 唱片悬停
    let expandTimer = null;
    this.disc.addEventListener('mouseenter', () => {
      expandTimer = setTimeout(() => this.expand(), 300);
      this.playBtn.style.opacity = 1;
      this.playBtn.style.pointerEvents = 'auto';
    });
    this.disc.addEventListener('mouseleave', () => {
      this.playBtn.style.opacity = 0;
      this.playBtn.style.pointerEvents = 'none';
    });

    // 点击唱片或播放按钮展开
    this.disc.addEventListener('click', () => this.expand());
    this.playBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      this.expand();
      if (this.audio.paused) this.audio.play();
      else this.audio.pause();
      this.updateDiscRotate();
    });

    // 控制栏鼠标交互
    this.controls.addEventListener('mouseenter', () => clearTimeout(this.hideTimer));
    this.controls.addEventListener('mouseleave', () => this.startHideTimer());

    // 控制栏按钮
    this.toggleBtn.addEventListener('click', () => {
      if (this.audio.paused) this.audio.play();
      else this.audio.pause();
      this.updateDiscRotate();
    });
    this.prevBtn.addEventListener('click', () => this.switchSong(this.current - 1));
    this.nextBtn.addEventListener('click', () => this.switchSong(this.current + 1));
    this.lyricBtn.addEventListener('click', () => {
      if (this.lyricWrapper.classList.contains('show')) {
        this.lyricWrapper.classList.remove('show');
      } else {
        this.lyricWrapper.classList.add('show');
      }
    });
    this.hideBtn.addEventListener('click', () => this.collapse());

    // 音频播放状态
    this.audio.addEventListener('play', () => this.updateDiscRotate());
    this.audio.addEventListener('pause', () => this.updateDiscRotate());
    this.audio.addEventListener('ended', () => this.switchSong(this.current + 1));

    // 展开后自动收起
    this.container.addEventListener('mouseleave', () => this.startHideTimer());
    this.container.addEventListener('mouseenter', () => clearTimeout(this.hideTimer));

    // 初始化
    this.updateDiscRotate();
    if (this.songs.length > 0) this.loadLyrics(this.songs[0].lyrics);

    // 自动播放
    if (this.options.autoplay) {
      setTimeout(() => this.audio.play(), 300);
    }
    // 初始化是否显示歌词
    if (this.options.showLyricOnInit) {
        console.log("显示歌词");
        this.lyricWrapper.classList.add('show');
    }else{
        console.log("不显示歌词");
        this.lyricWrapper.classList.remove('show');
    }
  }
}
